﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataLayer
{
    public class SchoolService
    {
        public List<MapPointDTO> GetSchools(decimal topleftlatitude, decimal topleftlongitude, decimal bottomrightlatitude, decimal bottomrightlongitude, int schooltypeid = 0)
        {

            using (var dl = new DataLayer.Model.UKSchoolsEntities())
            {
                //do a simple range search to find matching schools in the map view
                var matches = dl.Schools.Where(x =>
                    x.Latitude <= topleftlatitude &&
                    x.Latitude >= bottomrightlatitude &&
                    x.Longitude >= topleftlongitude &&
                    x.Longitude <= bottomrightlongitude &&
                    (x.SchoolTypeId == schooltypeid || schooltypeid == 0)
                ).ToList();
                //transform results into data transfer objects
                var results = new List<MapPointDTO>();
                matches.ForEach(x => 
                    results.Add(
                        new MapPointDTO()
                        {
                            Id = x.Id,
                            Name = x.Name,
                            Latitude = x.Latitude,
                            Longitude = x.Longitude
                        }
                    )
                );
                return results;
            }
        }

        public SchoolDTO GetSchool(int schoolid)
        {
            using (var dl = new DataLayer.Model.UKSchoolsEntities())
            {
                //get school by id
                var match = dl.Schools.Where(x => x.Id == schoolid).FirstOrDefault();
                SchoolDTO school = null;
                if (match != null)
                {
                    //tranform school into school data tranfer object
                    school = new SchoolDTO()
                    {
                        Id = match.Id,
                        Name = match.Name,
                        Address1 = match.Address1,
                        Address2 = match.Address2,
                        Address3 = match.Address3,
                        Postcode = match.Postcode,
                        SchoolTypeName = match.SchoolType.Name
                    };
                }
                return school;
            }
        }
    }
}
